package com.richardjaap.data;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.Timer;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class RouletteTable {

	private int tableId;
	private int amountOfPlayers;
	private ArrayList<Player> players;
	private int roundsInactive = 0;
	private ArrayList<Bet> bets = new ArrayList<Bet>();
	
	public RouletteTable(int id){
		this.players = new ArrayList<Player>();
		amountOfPlayers = 0;
		this.tableId = id;
		
		int delay = 10000; //milliseconds
		  ActionListener taskPerformer = new ActionListener() {
		      public void actionPerformed(ActionEvent evt) {
		    	  boolean isBlack = Math.random() > 0.5;
		    	  System.out.println(isBlack);
		          for(Bet b : bets)
		          {
		        	  System.out.print("bezig met: " + b);
		        	  if(b.isBlack() == isBlack)
		        	  {
		        		  for(Player p : players)
		        		  {
		        			  if(p.getId() == b.getPlayerId())
		        			  {
		        				  p.addCash(b.getAmount()*2);
		        				  System.out.println((b.getAmount() * 2) + " added to player: " + b.getPlayerId());
		        			  }
		        		  }
		        	  }
		          }
		    	  bets.clear();
		      }
		  };
		  new Timer(delay, taskPerformer).start();
	}
	
	public boolean buyIn(int playerId, double buyIn){
		Account account = getAccount(playerId);
		double cashTotal = account.getCashTotal();
		if(cashTotal < buyIn){
			return false;
		} else {
			account.setCashTotal(cashTotal -= buyIn);
			return true;
		}
	}
	
	private Account getAccount(int id){
		for(Player player : players){
			if(player.getId() == id){
				return Lobby.getInstance().getAccount(id);
			}
		}
		return null;
	}

	public int getTableId() {
		return tableId;
	}

	public ArrayList<Player> getPlayers() {
		return players;
	}
	
	public Player getPlayer(int id){
		for(Player player : players){
			if(player.getId() == id){
				return player;
			}
		}
		return null;
	}

	public boolean addPlayer(Player player) {
		if(!checkIfFull(amountOfPlayers)){
			players.add(player);
			amountOfPlayers++;
			return true;
		} else {
			System.out.println("The table is currently full");
			return false;
		}
	}
	
	public void removePlayer(int id){
		for(Player player : players){
			if(player.getId() == id){
				players.remove(player);
				amountOfPlayers--;
			}
		}
	}
	
	private boolean checkIfFull(int amount){
		if(amount == 10){
			return true;
		} else
		return false;
	}
	
	public boolean placeBet(Bet bet){
		bets.add(bet);
		return false;
	}
	
	
}
